package com.cll.task;

import com.cll.entity.Orders;
import com.cll.mapper.OrderMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

@Slf4j
@Component
public class OrderTask {

    @Autowired
    private OrderMapper orderMapper;

    /**
     *每分钟执行一次
     */
    @Scheduled(cron = "0 0/1 * * * ?")
    //@Scheduled(cron = "0/5 * * * * ?")
    public void payOrderLongTime(){
        //1.查询用户待支付和下单超过15分钟的所有订单列表List<Orders>
        //SQL语句:select * from orders where pay_status = 0 and order_time < #{当前时间-15}
        //先获取当前时间-15
        LocalDateTime orderTime = LocalDateTime.now().plusMinutes(-15);
        List<Orders> ordersList = orderMapper.findByStatusAndOrderTime(Orders.PENDING_PAYMENT,orderTime);

        //2.列表List<Orders>为空说明不存在超时未支付订单
        if (ordersList == null || ordersList.size() == 0){
            log.info("当前不存在超时未支付订单");
            return;
        }
        //3.遍历List<Orders>每个元素，设置每个订单状态为取消，取消原因
        for (Orders orders : ordersList) {
            //遍历修改超时未支付的状态
            orders.setStatus(Orders.CANCELLED);
            //修改时间
            orders.setOrderTime(LocalDateTime.now());
            //修改内容
            orders.setCancelReason("订单超时未支付,已取消");
            log.info("订单号:{}, 订单超时未支付,已取消",orders.getNumber());
            //调用orderMapper来更新
            orderMapper.update(orders);
        }
    }

    /**
     * 目标：每天1:00获取所有派送中的订单，进行定时处理为已完成状态
     */
    @Scheduled(cron = "0 0 1 * * ?")
    //@Scheduled(cron = "0/5 * * * * ?")
    public void processDeliveryOrder(){

        //1.查询所有派送中和1个小时前的订单列表集合List<Orders>
        //sql：select * from orders where status=4 and order_time<#{当前时间-60}
        LocalDateTime orderTime= LocalDateTime.now().plusMinutes(-60);
        List<Orders> ordersList = orderMapper.findByStatusAndOrderTime(Orders.DELIVERY_IN_PROGRESS,orderTime);

        //2.列表集合List<Orders>如果为null，不存在要自动处理的派送中的订单，结束程序
        if (ordersList == null || ordersList.size() == 0){
            log.info("当前不存在要自动处理的派送中的订单");
            return;
        }

        //3.列表集合List<Orders>如果不为null，遍历每个订单，设置订单已完成  这里使用的是新特性Lambda表达式
        ordersList.forEach(orders -> {
            orders.setStatus(Orders.COMPLETED);
            orderMapper.update(orders);
        });
    }
}
